#include <errno.h>
#include <sys/mman.h>
#include "LinkedList.h"

// 链表使用自分配的虚拟内存

template <typename T, typename CLock = CFakeLock>
class CShmList : public CLinkedListEx<T, CLock>
{
    typedef typename CLinkedList<T, CLock>::Node BaseNode;

public:
    struct ListNode : public CLinkedListEx<T, CLock>::Node
    {
        friend class CShmList;

        uint64_t nSize;

    public:
        ~ListNode() {}

    protected:
        ListNode(uint64_t sz) : nSize(sz) {}

    private:
        void *operator new(size_t sz, int iExt)
        {
            void *ptr = mmap(0, sz + iExt, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, 0, 0);

            if (MAP_FAILED == ptr)
            {
                printf("Error: mmap\tfile=%s\tline=%d\n", __FILE__, __LINE__);
                ptr = nullptr;
            }

            return ptr;
        }

        void operator delete(void *ptr)
        {
            if (nullptr != ptr)
            {
                ListNode *pNode = (ListNode *)ptr;
                int iRet = munmap(ptr, pNode->nSize);

                if (0 != iRet)
                    printf("Error: munmap error:%d\tfile=%s\tline=%d\n", errno, __FILE__, __LINE__);
            }
        }
    };

public:
    BaseNode *NewNode(int iExtLen) { return new (iExtLen) ListNode(sizeof(ListNode) + iExtLen); }

    // 自动调用Node及其父结构的析构函数,父结构需虚析构函数
    void DeleteNode(BaseNode *pNode) { delete (ListNode *)pNode; }

private:
    ListNode *NewNode() { return nullptr; }
    ListNode *NewNode(void *ptr) { return nullptr; }
};